package com.itlong.cloud.controller.sdkV2.intercom.server;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyProjectGetRoomInfoDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyProjectGetUnitInfoDTO;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.PO.AppUserProjectPO;
import com.itlong.cloud.POJO.PO.BuildInfoPO;
import com.itlong.cloud.POJO.PO.RoomInfoPO;
import com.itlong.cloud.POJO.PO.UnitInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.app.AppCreateBaiduFaceVO;
import com.itlong.cloud.POJO.VO.operate.OperateFaceApplyInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectUnitInfoVO;
import com.itlong.cloud.POJO.VO.sdk.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.PropertyPublicRoleEnum;
import com.itlong.cloud.enumerate.ecode.*;
import com.itlong.cloud.iottp.IIotBaiduFaceServiceClient;
import com.itlong.cloud.project.operate.IOperateFaceApplyServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.project.property.IPropertyRoomInfoServiceClient;
import com.itlong.cloud.project.property.IPropertyUnitInfoServiceClient;
import com.itlong.cloud.project.sdk.ICloudTalkSDKServerProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldRoomServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyHouseHoldInfoServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.file.ImgageUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.phonenumber.PhoneNoHandlerUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      云对讲SDK服务端项目信息Controller
 * </desc>
 *
 * @createDate 2018/05/16
 */
@RestController
@RequestMapping("/sdk/cloud/intercom/server")
public class SDKCloudTalkProjectController {

    private static Logger LOG = LoggerFactory.getLogger(SDKCloudTalkProjectController.class);

    @Value("${" + PlatformConstants.CLOUDTALK_SDK_USER_TOKEN_KEY + "}")
    private String CLOUDTALK_SDK_USER_TOKEN_KEY;

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Value("${" + PlatformConstants.LYKZ_ACCOUNT_SID + "}")
    String LYKZ_ACCOUNT_SID;
    @Value("${" + PlatformConstants.LYKZ_ACCOUNT_TOKEN + "}")
    String LYKZ_ACCOUNT_TOKEN;
    @Value("${" + PlatformConstants.LYKZ_APPID + "}")
    String LYKZ_APPID;
    @Value("${" + PlatformConstants.LYKZ_SOFT_VERSION + "}")
    String LYKZ_SOFT_VERSION;
    @Value("${" + PlatformConstants.LYKZ_URL + "}")
    String LYKZ_URL;
    @Value("${" + PlatformConstants.LYKZ_PORT + "}")
    String LYKZ_PORT;

    @Autowired
    private ICloudTalkSDKServerProjectServiceClient iCloudTalkSDKServerProjectServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    ISDKServerOldRoomServiceClient iSDKServerRoomClient;

    @Autowired
    private IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    private IPropertyRoomInfoServiceClient iPropertyRoomInfoServiceClient;

    @Autowired
    private IPropertyUnitInfoServiceClient iPropertyUnitInfoServiceClient;   //单元信息服务接口协议提供对象

    @Autowired
    private ISDKServerProjectServiceClient isdkServerProjectServiceClient;

    @Autowired
    IOperateFaceApplyServiceClient iOperateFaceApplyServiceClient;

    @Autowired
    IPropertyHouseHoldInfoServiceClient iPropertyHouseHoldInfoServiceClient;

    @Autowired
    IIotBaiduFaceServiceClient iIotBaiduFaceServiceClient;


    /**
     * <desc>
     *     添加或更新楼栋信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/05/17
     */
    @UnAuthAccessRequired
    public Object cloudTalkSDKAddOrUpdateBuild(CloudDeviceSDKDTO cloudTalkSDKServerBuildDTO) {
        try {
            String appId = cloudTalkSDKServerBuildDTO.getAppId();
            LOG.info("====添加楼栋入参：appid:" + appId + " projectId:" + cloudTalkSDKServerBuildDTO.getProjectId() + " buildJson:" + cloudTalkSDKServerBuildDTO.getBuildJson());
            String projectId = cloudTalkSDKServerBuildDTO.getProjectId();
            String buildJson = cloudTalkSDKServerBuildDTO.getBuildJson();
            JSONArray errArray = new JSONArray();
            List<CloudTalkSDKAddOrUpdateBuildInfoDTO> cloudTalkSDKAddOrUpdateBuildInfoDTOS;
            int count = 0;
            Date currentTime = new Date();
            List<BuildInfoPO> buildSaves = new ArrayList<>();
            List<BuildInfoPO> buildUpdates = new ArrayList<>();
            //解析buildJson
            try {
                JSONObject parseObject = JSONObject.parseObject(buildJson);
                cloudTalkSDKAddOrUpdateBuildInfoDTOS = JSONObject.parseObject(parseObject.getString("buildArr"), new TypeReference<List<CloudTalkSDKAddOrUpdateBuildInfoDTO>>() {
                });
            } catch (Exception e) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_PARSE_BUILDJSON_ERR.getErrorCode(),(Object) buildJson);
            }
            if (cloudTalkSDKAddOrUpdateBuildInfoDTOS == null || cloudTalkSDKAddOrUpdateBuildInfoDTOS.isEmpty()) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_BUILDARR_FORMAT_ERR.getErrorCode(),cloudTalkSDKAddOrUpdateBuildInfoDTOS);
            }
            for (CloudTalkSDKAddOrUpdateBuildInfoDTO buildDTO : cloudTalkSDKAddOrUpdateBuildInfoDTOS) {

                int groundFloorNum = buildDTO.getGroundFloorNum();
                int undergroundFloorNum = buildDTO.getUndergroundFloorNum();
                String undergroundFloorNumStr = undergroundFloorNum+"";
                if(undergroundFloorNumStr.startsWith("-")){
                    undergroundFloorNum = Integer.parseInt(undergroundFloorNumStr.substring(1,undergroundFloorNumStr.length()));
                }
                int sum = groundFloorNum+undergroundFloorNum;
                if (StringUtils.isEmpty(buildDTO.getBuildNum()) || StringUtils.isEmpty(buildDTO.getBuildName()) || buildDTO.getGroundFloorNum()==null || buildDTO.getUndergroundFloorNum()==null) {
                    errArray.add(JSONObject.toJSON(String.format("%s%s", " 缺少必要参数 ", buildDTO)));
                } else if (StringUtils.isEmpty(buildDTO.getBuildNum()) || !buildDTO.getBuildNum().trim().matches("\\d{3}") || StringUtils.isEmpty(buildDTO.getBuildName())) {
                    errArray.add(JSONObject.toJSON(String.format("%s%s", " 楼栋名称不能为空或楼栋编号长度必须为3位 ", buildDTO)));
                }else if(sum>99){
                    errArray.add(JSONObject.toJSON(String.format("%s%s", " 地面+地下楼层总数不能超过99 ", buildDTO)));
                } else {
                    // 判断新添加的楼栋信息是否已经存在
                    //楼栋层数默认99
                    int floorNum = buildDTO.getUndergroundFloorNum() + buildDTO.getGroundFloorNum();

                    Map<String, Object> param = new HashMap<>();
                    param.put("projectId", projectId);
                    param.put("buildNum", buildDTO.getBuildNum());
                    List<BuildInfoPO> buildInfos = iCloudTalkSDKServerProjectServiceClient.getBuildByParam(param);
                    //添加或更新
                    if (buildInfos != null && !buildInfos.isEmpty()) {
                        BuildInfoPO buildPO = buildInfos.get(0);
                        buildPO.setBuildName(buildDTO.getBuildName());
                        buildPO.setFloorNum(floorNum);
                        buildPO.setUpdateTime(currentTime);
                        buildPO.setGroundFloorNum(buildDTO.getGroundFloorNum());
                        buildPO.setUndergroundFloorNum(buildDTO.getUndergroundFloorNum());
                        buildUpdates.add(buildPO);
                    } else {
                        BuildInfoPO buildInfo = new BuildInfoPO(projectId, LogicIdUtil.bussinessId(), buildDTO.getBuildNum(), buildDTO.getBuildName(), floorNum);
                        buildInfo.setStatus(DataStatusEnum.NORMAL.getType());
                        buildInfo.setBuildType(1);
                        buildInfo.setGroundFloorNum(buildDTO.getGroundFloorNum());
                        buildInfo.setFloorNum(floorNum);
                        buildInfo.setUndergroundFloorNum(buildDTO.getUndergroundFloorNum());
                        buildInfo.setCreateTime(currentTime);
                        buildSaves.add(buildInfo);
                    }
                }
            }
            if (!buildUpdates.isEmpty()){
                iCloudTalkSDKServerProjectServiceClient.updateBuild(buildUpdates);
            }
            if (!buildSaves.isEmpty()){
                iCloudTalkSDKServerProjectServiceClient.saveBuild(buildSaves);
            }
            count = cloudTalkSDKAddOrUpdateBuildInfoDTOS.size()-errArray.size();
            Map<String,Object> result = new HashMap<>();
            result.put("count",count);
            result.put("errArray",JSONArray.toJSONString(errArray));
            return result;
        } catch (Exception e) {
            throw new DataAccessException("【SDK】添加或更新楼栋失败",e);
        }
    }

    /**
     * <desc>
     *     添加或更新单元信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/05/17
     */
    @UnAuthAccessRequired
    public Object cloudTalkSDKAddOrUpdateUnit(CloudDeviceSDKDTO cloudTalkSDKServerUnitDTO){
        try {
            String appId = cloudTalkSDKServerUnitDTO.getAppId();
            LOG.info("====添加单元入参：appid:" + appId + " projectId:" + cloudTalkSDKServerUnitDTO.getProjectId() + " unitJson:" + cloudTalkSDKServerUnitDTO.getUnitJson());

            String projectId = cloudTalkSDKServerUnitDTO.getProjectId();
            String unitJson = cloudTalkSDKServerUnitDTO.getUnitJson();
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            if (projectIdList == null || projectIdList.isEmpty() || !projectIdList.contains(projectId)) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode());
            }

            Date currentTime = new Date();
            JSONArray errArray = new JSONArray();
            int count = 0;
            List<CloudTalkSDKAddOrUpdateUnitInfoDTO> cloudTalkSDKAddOrUpdateUnitInfoDTOS;
            List<UnitInfoPO> unitSaves = new ArrayList<>();
            List<UnitInfoPO> unitUpdates = new ArrayList<>();
            try {
                JSONObject unitJ = JSONObject.parseObject(unitJson);
                cloudTalkSDKAddOrUpdateUnitInfoDTOS = JSONObject.parseObject(unitJ.getString("unitArr"), new TypeReference<List<CloudTalkSDKAddOrUpdateUnitInfoDTO>>() {
                });
            } catch (Exception e) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_PARSE_UNITJSON_ERR.getErrorCode(),(Object) unitJson);
            }
            if (cloudTalkSDKAddOrUpdateUnitInfoDTOS == null || cloudTalkSDKAddOrUpdateUnitInfoDTOS.isEmpty()){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_UNITARR_FORMAT_ERR.getErrorCode(),cloudTalkSDKAddOrUpdateUnitInfoDTOS);
            }
            for (CloudTalkSDKAddOrUpdateUnitInfoDTO cloudTalkSDKAddOrUpdateUnitInfoDTO : cloudTalkSDKAddOrUpdateUnitInfoDTOS) {
                if (!cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitNum().trim().matches("\\d{2}") || StringUtils.isEmpty(cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitName())) {
                    errArray.add(JSONObject.toJSON(" 单元名称不能为空或单元编号长度不等于2位 " + cloudTalkSDKAddOrUpdateUnitInfoDTO));
                } else {
                    //查询楼栋是否存在
                    Map<String, Object> param = new HashMap<>();
                    param.put("projectId", projectId);
                    param.put("buildNum", cloudTalkSDKAddOrUpdateUnitInfoDTO.getBuildNum());
                    List<BuildInfoPO> buildInfos = iCloudTalkSDKServerProjectServiceClient.getBuildByParam(param);
                    if (null != buildInfos && !buildInfos.isEmpty()) {
                        // 查询单元是否存在
                        BuildInfoPO buildInfo = buildInfos.get(0);
                        param.put("buildId", buildInfo.getBuildId());
                        param.put("unitNum", cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitNum());
                        List<UnitInfoPO> unitPOs = iCloudTalkSDKServerProjectServiceClient.getUnitByParam(param);
                        if (unitPOs != null && !unitPOs.isEmpty()) {
                            UnitInfoPO unitInfoPO = unitPOs.get(0);
                            unitInfoPO.setUnitName(cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitName());
                            String unitAlias = this.handlerUnitAlias(cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitAlias(), cloudTalkSDKAddOrUpdateUnitInfoDTO.getBuildNum(),
                                    cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitNum(), projectId);
                            if (StringUtils.isBlank(unitAlias)){
                                errArray.add(JSONObject.toJSON(" 单元代号不合法 " + cloudTalkSDKAddOrUpdateUnitInfoDTO));
                                continue;
                            }
                            unitInfoPO.setUnitAlias(unitAlias);
                            unitInfoPO.setUpdateTime(currentTime);
                            unitUpdates.add(unitInfoPO);
                        } else {
                            // 如果数据库中没有该数据，则添加
                            String unitAlias = this.handlerUnitAlias(cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitAlias(), cloudTalkSDKAddOrUpdateUnitInfoDTO.getBuildNum(),
                                    cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitNum(), projectId);
                            if (StringUtils.isBlank(unitAlias)){
                                errArray.add(JSONObject.toJSON(" 单元代号不合法 " + cloudTalkSDKAddOrUpdateUnitInfoDTO));
                                continue;
                            }
                            UnitInfoPO unitInfoPO = new UnitInfoPO(projectId, buildInfo.getBuildId(), LogicIdUtil.bussinessId(), cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitNum(),
                                    cloudTalkSDKAddOrUpdateUnitInfoDTO.getUnitName(), unitAlias);
                            unitInfoPO.setCreateTime(currentTime);
                            unitInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
//                            count += iCloudTalkSDKServerProjectServiceClient.saveUnit(unitInfoPO);
                            unitSaves.add(unitInfoPO);
                        }
                    } else {
                        errArray.add(JSONObject.toJSON(" 该楼栋编号的楼栋不存在 " + cloudTalkSDKAddOrUpdateUnitInfoDTO));
                    }
                }
            }
            if (!unitUpdates.isEmpty()){
                iCloudTalkSDKServerProjectServiceClient.updateUnit(unitUpdates);
            }
            if (!unitSaves.isEmpty()){
                iCloudTalkSDKServerProjectServiceClient.saveUnit(unitSaves);
            }
            count = cloudTalkSDKAddOrUpdateUnitInfoDTOS.size()-errArray.size();
            Map<String,Object> result = new HashMap<>();
            result.put("count",count);
            result.put("errArray",JSONArray.toJSONString(errArray));
            return result;
        } catch (Exception e) {
            throw new DataAccessException("【SDK】添加或更新单元失败",e);
        }
    }

    /**
     *<desc>
     *     处理单元代号
     *</desc>
     *
     * @param unitAlias 单元代号
     * @param buildNum 楼栋编号
     * @param unitNum 单元编号
     * @param projectId 项目id
     * @return 处理过后的unitAlias
     * @author wangzhi
     * @createDate 2018/05/24
     */
    private String handlerUnitAlias(String unitAlias,String buildNum,String unitNum,String projectId){
        if (StringUtils.isBlank(unitAlias)){
            // 若为空则默认生成
            return (String.format("%s%s", buildNum, unitNum)).replaceAll("^(0+)", "");
        } else {
            // 若不为空，则进行校验
            int intUnitAlias = StringHandlerUtil.strToIntDef(unitAlias, 0);
            if ((!NumberHandlerUtil.isInRange(intUnitAlias, PlatformConstants.MIN_UNIT_ALIAS,
                    PlatformConstants.MAX_UNIT_ALIAS)
                    || (intUnitAlias == PlatformConstants.INVALID_ALIAS))) {
                return null;
            }

            //自动消去楼栋单元代号可能的前置0，如 "0301"->"301", "00301"->"301"
            unitAlias = unitAlias.replaceAll("^(0+)", "");

            //楼栋单元代号在当前项目内不允许重复，即不同单元编号具有同一单元代号则不合法，返回null
            PropertyProjectUnitInfoVO propertyProjectUnitInfoVO = getUnitInfoByUnitAlias(unitAlias, projectId);
            if (null != propertyProjectUnitInfoVO && !StringHandlerUtil.compareStrWithOutEmpty(propertyProjectUnitInfoVO.getUnitNum(),unitNum)) {
                return null;
            }
            return unitAlias;
        }
    }

    /**
     * <desc>
     *      根据楼栋单元代号精确查询单元信息
     * </desc>
     *
     * @param unitAlias 单元代号
     * @return 单元信息
     * @author wangzhi
     * @createDate 2018/05/24
     */
    private PropertyProjectUnitInfoVO getUnitInfoByUnitAlias(String unitAlias, String projectId) {
        PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO = new PropertyProjectGetUnitInfoDTO();
        propertyProjectGetUnitInfoDTO.setProjectId(projectId);
        propertyProjectGetUnitInfoDTO.setUnitAlias(unitAlias);
        return iPropertyUnitInfoServiceClient.getOneUnitInfo(propertyProjectGetUnitInfoDTO);
    }

    /**
     * <desc>
     *     添加或更新房间信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/05/18
     */
    @UnAuthAccessRequired
    public Object cloudTalkSDKAddOrUpdateRoom(CloudDeviceSDKDTO cloudTalkSDKServerRoomDTO){

        try {
            String appId = cloudTalkSDKServerRoomDTO.getAppId();
            LOG.info("====SDK添加房间入参：appid:" + appId + " projectId:" + cloudTalkSDKServerRoomDTO.getProjectId() + " roomJson:" + cloudTalkSDKServerRoomDTO.getRoomJson());

            String projectId = cloudTalkSDKServerRoomDTO.getProjectId();
            String roomJson = cloudTalkSDKServerRoomDTO.getRoomJson();

            Date currentTime = new Date();
            JSONArray errArray = new JSONArray();
            int count = 0;
            List<CloudTalkSDKAddOrUpdateRoomInfoDTO> cloudTalkSDKAddOrUpdateRoomInfoDTOS;
            List<RoomInfoPO> roomSaves = new ArrayList<>();
            List<RoomInfoPO> roomUpdates = new ArrayList<>();
            try {
                JSONObject roomJ = JSONObject.parseObject(roomJson);
                cloudTalkSDKAddOrUpdateRoomInfoDTOS = JSONObject.parseObject(roomJ.getString("roomArr"), new TypeReference<List<CloudTalkSDKAddOrUpdateRoomInfoDTO>>() {
                });
            } catch (Exception e) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_PARSE_ROOMJSON_ERR.getErrorCode(),(Object) roomJson);
            }
            if (cloudTalkSDKAddOrUpdateRoomInfoDTOS == null || cloudTalkSDKAddOrUpdateRoomInfoDTOS.isEmpty()){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ROOMARR_FORMAT_ERR.getErrorCode(),cloudTalkSDKAddOrUpdateRoomInfoDTOS);
            }
            for (CloudTalkSDKAddOrUpdateRoomInfoDTO cloudTalkSDKAddOrUpdateRoomInfoDTO : cloudTalkSDKAddOrUpdateRoomInfoDTOS) {
                String roomNum = cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomNum();
                if (StringUtils.isBlank(cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomName()) || !roomNum.trim().matches("\\d{4}")) {
                    errArray.add(" 房间名称不能为空或房间编号长度不等于4位:" + cloudTalkSDKAddOrUpdateRoomInfoDTO);
                    continue;
                }
                Map<String, Object> param = new HashMap<>();
                param.put("projectId", projectId);
                param.put("buildNum", cloudTalkSDKAddOrUpdateRoomInfoDTO.getBuildNum());
                param.put("unitNum", cloudTalkSDKAddOrUpdateRoomInfoDTO.getUnitNum());
                List<UnitInfoPO> unitPOs = iCloudTalkSDKServerProjectServiceClient.getUnitByParam(param);
                if (unitPOs != null && !unitPOs.isEmpty()) {
                    UnitInfoPO unitInfoPO = unitPOs.get(0);
                    param.put("unitId", unitInfoPO.getUnitId());
                    param.put("roomNum", roomNum);
                    List<RoomInfoPO> roomPOs = iCloudTalkSDKServerProjectServiceClient.getRoomByParam(param);
                    // 如果数据库存在该数据，则更新
                    if (roomPOs != null && !roomPOs.isEmpty()) {
                        RoomInfoPO roomPO = roomPOs.get(0);
                        roomPO.setRoomName(cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomName());
                        roomPO.setLiftDoorType(cloudTalkSDKAddOrUpdateRoomInfoDTO.getLiftDoorType());
                        roomPO.setRoomType(cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomType());

                        // 处理房间代号roomAlias
                        String roomAlias = this.simpleHandlerRoomAlias(cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomAlias(), roomPO.getUnitId(),cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomNum());
                        if (StringUtils.isBlank(roomAlias)){
                            errArray.add(JSONObject.toJSON(" 房间代号非法 " + cloudTalkSDKAddOrUpdateRoomInfoDTO));
                            continue;
                        }
                        roomPO.setRoomAlias(roomAlias);

                        // 处理房屋呼叫号码phoneNo,外地号码前面+0
                        String projectCityName = iOperateProjectServiceClient.getProjectCityName(projectId);
                        if(StringUtils.isNotEmpty(cloudTalkSDKAddOrUpdateRoomInfoDTO.getPhoneNo())){
                            String phoneNo = PhoneNoHandlerUtil.handlerPhoneNoLocationAdd0OrSub0(projectCityName, cloudTalkSDKAddOrUpdateRoomInfoDTO.getPhoneNo());
                            roomPO.setPhoneNo(phoneNo);
                        }

                        roomPO.setUpdateTime(currentTime);
                        roomUpdates.add(roomPO);
                    } else {
                        // 如果数据库中没有该房间数据，则添加
                        // 处理房间代号roomAlias
                        String roomAlias = this.simpleHandlerRoomAlias(cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomAlias(), unitInfoPO.getUnitId(),cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomNum());
                        if (StringUtils.isBlank(roomAlias)){
                            errArray.add(JSONObject.toJSON(" 房间代号非法 " + cloudTalkSDKAddOrUpdateRoomInfoDTO));
                            continue;
                        }
                        RoomInfoPO roomInfoPO = new RoomInfoPO(projectId, unitInfoPO.getBuildId(), unitInfoPO.getUnitId(), LogicIdUtil.bussinessId(),
                                roomNum, cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomName(), roomAlias, cloudTalkSDKAddOrUpdateRoomInfoDTO.getLiftDoorType());
                        roomInfoPO.setRoomType(cloudTalkSDKAddOrUpdateRoomInfoDTO.getRoomType());

                        // 处理手机号码
                        if(StringUtils.isNotEmpty(cloudTalkSDKAddOrUpdateRoomInfoDTO.getPhoneNo())){
                            String projectCityName = iOperateProjectServiceClient.getProjectCityName(projectId);
                            String phoneNo = PhoneNoHandlerUtil.handlerPhoneNoLocationAdd0OrSub0(projectCityName, cloudTalkSDKAddOrUpdateRoomInfoDTO.getPhoneNo());
                            roomInfoPO.setPhoneNo(phoneNo);
                        }

                        roomInfoPO.setCreateTime(currentTime);
                        roomInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                        roomSaves.add(roomInfoPO);
                    }
                }else{
                    errArray.add(JSONObject.toJSON(" 该单元编号的楼栋单元不存在 " + cloudTalkSDKAddOrUpdateRoomInfoDTO));
                }
            }
            if (!roomUpdates.isEmpty()){
                iCloudTalkSDKServerProjectServiceClient.updateRoom(roomUpdates);
            }
            if (!roomSaves.isEmpty()){
                iCloudTalkSDKServerProjectServiceClient.saveRoom(roomSaves);
            }
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            count = cloudTalkSDKAddOrUpdateRoomInfoDTOS.size()-errArray.size();
            Map<String,Object> result = new HashMap<>();
            result.put("count",count);
            result.put("errArray",JSONArray.toJSONString(errArray));
            return result;
        } catch (Exception e) {
            throw new DataAccessException("【SDK】添加或更新房间失败",e);
        }

    }

    /**
     * <desc>
     *     处理房间代号，不合法或为空则返回空
     * </desc>
     *
     * @param roomAlias 待处理的房间代号
     * @param unitId 单元id
     * @param roomNum 房间编号
     * @return 处理后的房间代号
     * @author wangzhi
     * @createDate 2018/05/24
     */
    private String simpleHandlerRoomAlias(String roomAlias,String unitId,String roomNum){
        if (StringUtils.isBlank(roomAlias)){
            return roomNum.replaceAll("^(0+)", "");
        } else {
            int intRoomAlias = StringHandlerUtil.strToIntDef(roomAlias, -1);
            int intRoomNum = StringHandlerUtil.strToIntDef(roomNum, -1);
            if (!((intRoomNum == 0) && (intRoomAlias == 0))){ //房号为0时允许房屋呼叫号码为0
                // 房间代号非法，返回空
                if ((!NumberHandlerUtil.isInRange(intRoomAlias, PlatformConstants.MIN_ROOM_ALIAS,
                        PlatformConstants.MAX_ROOM_ALIAS)
                        || (intRoomAlias == PlatformConstants.INVALID_ALIAS))) {
                    return null;
                }
            }
            // 先消去房间代号前面可能存在的0
            roomAlias = roomAlias.replaceAll("^(0+)", "");
            // 同一单元下不可以存在相同的房间代号，即不同的房间编号具有相同的房间代号则不合法
            RoomInfoPO roomInfoPO = getRoomInfoByRoomAlias(roomAlias, unitId);
            if (null != roomInfoPO && !StringHandlerUtil.compareStrWithOutEmpty(roomInfoPO.getRoomNum(),roomNum)) {
                return null;
            }
            if (intRoomAlias == 0){
                return "0000";
            }
            return roomAlias;
        }
    }

    /**
     *<desc>
     *      处理房间代号，不合法或为空则自动生成
     *</desc>
     *
     * @param roomAliasFromParam 参数中的房间代号
     * @param roomAliasFromExist 已经存在的房间代号
     * @param unitId 单元id
     * @param roomNum 房间编号
     * @return 处理后的房间代号
     * @author wangzhi
     * @createDate 2018/05/18
     */
    private String handlerRoomAlias(String roomAliasFromParam, String roomAliasFromExist, String unitId,String roomNum) {
        // 参数中roomAlias不为空的情况
        if (StringUtils.isNotBlank(roomAliasFromParam)) {
            if (StringHandlerUtil.compareStrWithOutEmpty(roomAliasFromParam,roomAliasFromExist)){
                return roomAliasFromExist;
            }
            int intRoomAlias = StringHandlerUtil.strToIntDef(roomAliasFromParam, -1);
            int intRoomNum = StringHandlerUtil.strToIntDef(roomNum, -1);

            if (!((intRoomNum == 0) && (intRoomAlias == 0))){ //房号为0时允许房屋呼叫号码为0
                // 房间代号非法，返回已存在的房间代号，若已存在的为空，则返回空
                if ((!NumberHandlerUtil.isInRange(intRoomAlias, PlatformConstants.MIN_ROOM_ALIAS,
                        PlatformConstants.MAX_ROOM_ALIAS)
                        || (intRoomAlias == PlatformConstants.INVALID_ALIAS))) {
                    return StringUtils.isBlank(roomAliasFromExist)?roomNum.replaceAll("^(0+)", ""):roomAliasFromExist;
                }
            }

            //访客呼叫码在当前单元内不允许重复
            RoomInfoPO roomInfoPO = getRoomInfoByRoomAlias(roomAliasFromParam, unitId);
            if (null != roomInfoPO) {
                if (StringHandlerUtil.compareStrWithOutEmpty(roomInfoPO.getRoomAlias(),roomAliasFromExist)) {
                    return roomAliasFromExist;
                }else{
                    return roomNum.replaceAll("^(0+)", "");
                }
            }
            if (intRoomAlias == 0){
                return "0000";
            } else {  // 自动消去房屋被呼号码可能的前置0，如 "0301"->"301", "00301"->"301"
                roomAliasFromParam = roomAliasFromParam.replaceAll("^(0+)", "");
            }
            return roomAliasFromParam;
        }else{ // 参数中roomAlias为空的情况
            if (StringUtils.isNotBlank(roomAliasFromExist)){
                return roomAliasFromExist;
            }else{
                return roomNum.replaceAll("^(0+)", "");
            }
        }
    }


    /**
     * <desc>
     *      根据访客呼叫码和单元Id精确查询房屋信息
     * </desc>
     *
     * @param roomAlias 访客呼叫码
     * @param unitId    单元Id
     * @return 房屋信息
     * @author LewisLouis
     * @createDate 2017-10-18
     */
    private RoomInfoPO getRoomInfoByRoomAlias(String roomAlias, String unitId) {
        PropertyProjectGetRoomInfoDTO propertyProjectGetRoomInfoDTO = new PropertyProjectGetRoomInfoDTO();
        propertyProjectGetRoomInfoDTO.setUnitId(unitId);
        propertyProjectGetRoomInfoDTO.setRoomAlias(roomAlias);
        return iPropertyRoomInfoServiceClient.getOneSimpleRoomInfo(propertyProjectGetRoomInfoDTO);
    }

    /**
     * <desc>
     *      批量往存在的房间中添加住户
     * <desc/>
     *
     * @return  MessageVO   标准格式化响应结果
     * @author JuGuang.S
     * @createDate 2018/05/17
     */
    @UnAuthAccessRequired
    public Object cloudTalkSDKAddUser(CloudDeviceSDKDTO cloudTalkSDKServerAddUserDTO) {
        try {
            String appId = cloudTalkSDKServerAddUserDTO.getAppId();
            String projectId = cloudTalkSDKServerAddUserDTO.getProjectId();
            String userJson = cloudTalkSDKServerAddUserDTO.getUserJson();
            String responseTimestamp = new Date().getTime() + "";

            if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(userJson)) {
                return new MessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //根据项目编号和角色为开发者账号查询当前项目绑定的灵云快智的应用账号信息
            String lykzAppId = iCloudTalkSDKServerProjectServiceClient.getBingLykzAppId(projectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId(),appId);
            if(StringUtils.isEmpty(lykzAppId)){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_SDK_PROJECT_BLING.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
            }
            JSONArray errarray = new JSONArray();
            List<CloudTalkSDKServerUserSaveDTO> userSdkDtos = null;
            try {
                JSONObject userObject = JSONObject.parseObject(userJson);
                String userArr = userObject.getString("userArr");
                userSdkDtos = JSONObject.parseObject(userArr, new TypeReference<List<CloudTalkSDKServerUserSaveDTO>>() {
                });
            } catch (Exception e) {
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_PARSE_USERJSON_ERR.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
            }
            if(userSdkDtos.isEmpty() || userSdkDtos == null){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_USER_ROOM_ERR.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
            }

            List<SDKSaveAppUserDTO> saveAppUserDTOs = new ArrayList<>();
            for (CloudTalkSDKServerUserSaveDTO userSdkDto : userSdkDtos) {
                String userId =  LogicIdUtil.userBusinessId();
                String phoneNo = userSdkDto.getPhoneNo();
                Integer houseType = userSdkDto.getHouseType();
                String realName = userSdkDto.getRealName();
                Integer gender = userSdkDto.getGender();
                userSdkDto.setUserId(userId);

                if (StringUtils.isEmpty(realName) || gender == null) {
                    return new SDKMessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
                }

                if (StringUtils.isEmpty(phoneNo) || !phoneNo.matches(PlatformConstants.USER_PHONENUM_REGIX)) {
                    return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_USER_PHONE_ERR.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
                }

                if (StringUtils.isNotEmpty(userSdkDto.getImageStr())) {
                    //判断项目是否开启人脸识别,并查询是否有百度库key
                    OperateFaceApplyInfoVO operateFaceApplyInfoVO = iOperateFaceApplyServiceClient.getFaceByProjectId(projectId);
                    if (operateFaceApplyInfoVO == null) {
                        return new SDKMessageVO(AppErrorCodeEnum.PROJECT_FACE_APPID_INEXISTENCE_BY_CLOUD_TALK.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
                    }
                    AppCreateBaiduFaceVO appCreateBaiduFaceVO = new AppCreateBaiduFaceVO();
                    appCreateBaiduFaceVO.setAPP_ID(operateFaceApplyInfoVO.getAppId());
                    appCreateBaiduFaceVO.setAPI_KEY(operateFaceApplyInfoVO.getApiKey());
                    appCreateBaiduFaceVO.setSECRET_KEY(operateFaceApplyInfoVO.getSecretKey());
                    appCreateBaiduFaceVO.setFaceScore(operateFaceApplyInfoVO.getFaceScore() == 0F ? 80F : operateFaceApplyInfoVO.getFaceScore());
                    //判断图片分辨率
                    BufferedImage bi = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(userSdkDto.getImageStr())));
                    int width = bi.getWidth();
                    int height = bi.getHeight();
                    if (width < 640 || height < 480 || width > 2560 || height > 2560) {
                        return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESOLUTION_RATIO_ERROR.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
                    }
                    //保存图片
                    String uploadFilePath = uploadImageFile(new BASE64Decoder().decodeBuffer(userSdkDto.getImageStr()), "png", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
//                        String uploadFilePath = "https://img.jia-r.com/baiduFaceCreateFile/18/09/11/180911093718607T4WQ.jpeg";
                    appCreateBaiduFaceVO.setImageUrl(uploadFilePath);
                    appCreateBaiduFaceVO.setUid(userSdkDto.getUserId());
                    appCreateBaiduFaceVO.setRequestId(appCreateBaiduFaceVO.getRequestId());
                    appCreateBaiduFaceVO.setAppSecret(appCreateBaiduFaceVO.getAppSecret());
                    appCreateBaiduFaceVO.setResponseTimestamp(appCreateBaiduFaceVO.getResponseTimestamp());

                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", userSdkDto.getUserId());
                    SDKMessageVO messageVO = this.checkFace(appCreateBaiduFaceVO);
                    if (messageVO != null) {
                        messageVO.setData(map);
                        return messageVO;
                    }
                }

                List<SDKRoomInfoSaveDTO> roomDTOs = userSdkDto.getRoomArr();
                List<SDKRoomInfoSaveDTO> saveRoomDTOs = new ArrayList<>();
                if (null != roomDTOs && roomDTOs.size() > 0) {
                    //验证房间是否存在
                    for (SDKRoomInfoSaveDTO roomDTO : roomDTOs) {
                        String buildNum = roomDTO.getBuildNum();
                        String unitNum = roomDTO.getUnitNum();
                        String roomNum = roomDTO.getRoomNum();
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("projectId", projectId);
                        paramMap.put("buildNum", buildNum);
                        paramMap.put("unitNum", unitNum);
                        paramMap.put("roomNum", roomNum);
                        List<RoomInfoPO> existRooms = iCloudTalkSDKServerProjectServiceClient.getRoomByPiBnUnRn(paramMap);
                        if (existRooms == null || existRooms.isEmpty()) {
                            errarray.add(JSONObject.toJSON("请检查地址是否存在：buildNum:" + buildNum + " unitNum:" + unitNum + " roomNum:" + roomNum));
                            continue;
//                            return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ROOM_ADDRESS_IS_EXIST.getErrorCode());
                        }
                        if(userSdkDto.getHouseType()==1){
                            if(iCloudTalkSDKServerProjectServiceClient.getIsOwnerUser(paramMap)>0){
                                errarray.add(JSONObject.toJSON("该房间下已有户主：buildNum:" + buildNum + " unitNum:" + unitNum + " roomNum:" + roomNum));
                                continue;
                            }
                        }
                        if(userSdkDto.getHouseType()==2 || userSdkDto.getHouseType()==3){
                            if(iCloudTalkSDKServerProjectServiceClient.getIsOwnerUser(paramMap)==0){
                                errarray.add(JSONObject.toJSON("该房间下没有户主：buildNum:" + buildNum + " unitNum:" + unitNum + " roomNum:" + roomNum+"不能添加家属和租客"));
                                continue;
                            }
                        }
                        SDKRoomInfoSaveDTO sdkRoomInfoSaveDTO = new SDKRoomInfoSaveDTO();
                        BeanUtils.copyProperties(existRooms.get(0),sdkRoomInfoSaveDTO);
                        saveRoomDTOs.add(sdkRoomInfoSaveDTO);
                    }
                }
                SDKSaveAppUserDTO sdkSaveAppUserDTO = new SDKSaveAppUserDTO(projectId, appId, phoneNo, houseType, saveRoomDTOs, null);
                sdkSaveAppUserDTO.setRealName(realName);
                sdkSaveAppUserDTO.setGender(gender);
                sdkSaveAppUserDTO.setLykzAppId(lykzAppId);
                sdkSaveAppUserDTO.setUserId(userId);

                saveAppUserDTOs.add(sdkSaveAppUserDTO);
            }
            if (!errarray.isEmpty()) {
//                Map<String,Object> returnData = new HashMap<>();
//                returnData.put("modifyMessage", "用户信息错误/缺少必要参数  reqParams:" + errarray.toJSONString());
//                returnData.put("code","1");
                return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "用户信息错误/缺少必要参数  reqParams:" + errarray.toJSONString(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
//                return returnData;
            }else{
                if (saveAppUserDTOs == null || saveAppUserDTOs.isEmpty()) {
                    return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_USER_ROOM_ERR.getErrorCode());
                }
                Map<String, Object> countMap = iCloudTalkSDKServerProjectServiceClient.addUserRoomInfo(saveAppUserDTOs);

                for (CloudTalkSDKServerUserSaveDTO userSdkDto : userSdkDtos) {
                    String imageStr = userSdkDto.getImageStr();
                    if (StringUtils.isNotEmpty(imageStr)) {
                        //判断项目是否开启人脸识别,并查询是否有百度库key
                        OperateFaceApplyInfoVO operateFaceApplyInfoVO = iOperateFaceApplyServiceClient.getFaceByProjectId(projectId);
                        if (operateFaceApplyInfoVO == null) {
                            return new SDKMessageVO(AppErrorCodeEnum.PROJECT_FACE_APPID_INEXISTENCE_BY_CLOUD_TALK.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
                        }
                        AppCreateBaiduFaceVO appCreateBaiduFaceVO = new AppCreateBaiduFaceVO();
                        appCreateBaiduFaceVO.setAPP_ID(operateFaceApplyInfoVO.getAppId());
                        appCreateBaiduFaceVO.setAPI_KEY(operateFaceApplyInfoVO.getApiKey());
                        appCreateBaiduFaceVO.setSECRET_KEY(operateFaceApplyInfoVO.getSecretKey());
                        appCreateBaiduFaceVO.setFaceScore(operateFaceApplyInfoVO.getFaceScore() == 0F ? 80F : operateFaceApplyInfoVO.getFaceScore());
                        //判断图片分辨率
                        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(imageStr)));
                        int width = bi.getWidth();
                        int height = bi.getHeight();
                        if (width < 640 || height < 480 || width > 2560 || height > 2560) {
                            return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESOLUTION_RATIO_ERROR.getErrorCode(), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "");
                        }
                        //保存图片
                        String uploadFilePath = uploadImageFile(new BASE64Decoder().decodeBuffer(imageStr), "png", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
//                        String uploadFilePath = "https://img.jia-r.com/baiduFaceCreateFile/18/09/11/180911093718607T4WQ.jpeg";
                        appCreateBaiduFaceVO.setImageUrl(uploadFilePath);
                        appCreateBaiduFaceVO.setUid(userSdkDto.getUserId());
                        appCreateBaiduFaceVO.setRequestId(appCreateBaiduFaceVO.getRequestId());
                        appCreateBaiduFaceVO.setAppSecret(appCreateBaiduFaceVO.getAppSecret());
                        appCreateBaiduFaceVO.setResponseTimestamp(appCreateBaiduFaceVO.getResponseTimestamp());

                        Map<String, Object> map = new HashMap<>();
                        map.put("userId", userSdkDto.getUserId());
                        SDKMessageVO messageVO = this.checkFace(appCreateBaiduFaceVO);
                        if (messageVO != null) {
                            messageVO.setData(map);
                            return messageVO;
                        }

                        //保存数据
                        messageVO = this.saveUserFace(userSdkDto.getUserId(), uploadFilePath, appCreateBaiduFaceVO.getRequestId(), responseTimestamp,projectId,userSdkDto.getPhoneNo(),userSdkDto.getRealName(), appCreateBaiduFaceVO);
                        if (messageVO != null) {
                            messageVO.setData(map);
                            return messageVO;
                        }
                    }

                }

                Integer existUser = (Integer) countMap.get("existUser");
                Integer addUserCount = (Integer) countMap.get("addUserCount");
                Map<String,Object> returnData = new HashMap<>();
//                returnData.put("modifyMessage",String.format("%s%s%s%s", "本次共添加：", addUserCount, "个用户", (existUser > 0 ? "," + existUser + "个用户已经存在" : "")));
                returnData.put("sipArr",countMap.get("sipArr"));
                returnData.put("code","0");
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), String.format("%s%s%s%s", "本次共添加：", addUserCount, "个用户", (existUser > 0 ? "," + existUser + "个用户已经存在" : "")), cloudTalkSDKServerAddUserDTO.getRequestId(), responseTimestamp, "",returnData);
//                return returnData;
            }
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端_CloudTalkSDKServerProjectController_cloudTalkSDKAddUser】项目批量添加用户房间异常", e);
        }
    }

    /**
     * <desc>
     *      项目下的启用禁用用户
     * <desc/>
     *
     * @return  MessageVO   标准格式化响应结果
     * @author JuGuang.S
     * @createDate 2018/05/21
     */
    @UnAuthAccessRequired
    public Object modifyUserStatus(CloudTalkSDKServerUserStatusDTO userStatusDTO) throws Exception{
            String appId = userStatusDTO.getAppId();
            String projectId = userStatusDTO.getProjectId();
            String userIds = userStatusDTO.getUserIds();
            String status = userStatusDTO.getUserProjectStatus();
            if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(userIds) || StringUtils.isEmpty(status)){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode(),userStatusDTO.getRequestId(),userStatusDTO.getResponseTimestamp(),"");
            }

            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            String projectStr = null;
            if(!projectIdList.isEmpty() && projectIdList!=null){
                projectStr = String.join(",",projectIdList);
            }
            if(!projectStr.contains(projectId)){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode(),userStatusDTO.getRequestId(),userStatusDTO.getResponseTimestamp(),"");
            }
            String[] userIdArr = StringHandlerUtil.splitString(userIds);
            for(String userId : userIdArr){
                //校验所要禁用户用的用户在该项目下是否存在
                Integer count = iCloudTalkSDKServerProjectServiceClient.userIsExist(projectId,userId);
                if(count == 0){
                    return new MessageVO(CloudTalkErrorCodeEnum.SERVER_PROJECT_USER_ISNOT_EXIST.getErrorCode());
                }
            }

            for(String userId : userIdArr){
                Map<String,Object> params = new HashMap<>();
                params.put("projectId",projectId);
                params.put("userId",userId);
                params.put("status",Integer.parseInt(status));
                params.put("updateTime",new Date());
                iCloudTalkSDKServerProjectServiceClient.modifyUserStatus(params);
            }

        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),userStatusDTO.getRequestId(), userStatusDTO.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),userStatusDTO.getRequestId(),userStatusDTO.getResponseTimestamp(),
                        userStatusDTO.getAppSecret()));
    }

    /**
     * <desc>
     *     获取项目的楼栋信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/08
     */
    @UnAuthAccessRequired
    public Object getBuildList(CloudDeviceSDKDTO dto){
        try {
            String appId = dto.getAppId();
            String projectId = dto.getProjectId();
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            if (projectIdList == null || projectIdList.isEmpty() || !projectIdList.contains(projectId)) {
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), isdkServerProjectServiceClient.getBuildList(dto));
        } catch (Exception e) {
            throw new DataAccessException("【SDK】获取项目的楼栋信息列表失败",e);
        }
    }

    /**
     * <desc>
     *     获取项目楼栋的单元信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/05/23
     */
    @UnAuthAccessRequired
    public Object getUnitList(CloudDeviceSDKDTO dto){
        try {
            String appId = dto.getAppId();
            String projectId = dto.getProjectId();
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            if (projectIdList == null || projectIdList.isEmpty() || !projectIdList.contains(projectId)) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode());
            }

            Page<SDKProjectUnitInfoVO> sdkProjectUnitInfoVOPage = isdkServerProjectServiceClient.getUnitList(dto);

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), sdkProjectUnitInfoVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【SDK】获取项目楼栋的单元信息列表失败",e);
        }
    }

    /**
     * <desc>
     *     获取项目房间信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/8
     */
    @UnAuthAccessRequired
    public Object getRoomList(CloudDeviceSDKDTO dto){
        try {
            String appId = dto.getAppId();
            String projectId = dto.getProjectId();
            // 校验开发者账号是否有该项目的权限
            Page<SDKProjectRoomInfoVO> sdkProjectUnitInfoVO = isdkServerProjectServiceClient.getRoomList(dto);

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), sdkProjectUnitInfoVO);
        } catch (Exception e) {
            throw new DataAccessException("【SDK】获取项目楼栋的单元信息列表失败",e);
        }
    }

    @UnAuthAccessRequired
    public Object getProjectList() {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerGetProjectInfoPageDTO pageDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerGetProjectInfoPageDTO.class, request);

            //判断接入凭证
            if(StringUtils.isBlank(pageDTO.getAppId())){
                return new MessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<SDKServerProjectInfoListPageVO> pageVO = iCloudTalkSDKServerProjectServiceClient.getProjectList(pageDTO);
            SDKServerProjectInfoListVO sdkServerProjectInfoListVO = new SDKServerProjectInfoListVO();
            sdkServerProjectInfoListVO.setTotalNumber(pageVO.getPage().getTotalNumber());
            sdkServerProjectInfoListVO.setProjectInfoArr(pageVO.getRows());
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),sdkServerProjectInfoListVO);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",LogDescConstant.SDK_SERVER_PROJECT_INFO_LOG_DESC);
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK服务端】获取项目信息列表",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      上传苹果推送证书
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/22
     */
    @ResponseBody
    @PostMapping(path = "/uploadApplePush")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_UPLOAD_APPLE_LOG_DESC)
    public Object uploadApplePush(HttpServletRequest request){
        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerUploadApplePushDTO cloudTalkSDKServerUploadApplePushDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerUploadApplePushDTO.class, request);
            String appId = cloudTalkSDKServerUploadApplePushDTO.getAppId();
            String projectId = cloudTalkSDKServerUploadApplePushDTO.getProjectId();
            LOG.info("====SDK添加设备入参：appId：" + appId + " projectId:" + projectId);
            // 解密项目id
//            projectId = DesEncryptUtil.projectIdDesEncrypt(projectId) == null ? projectId : DesEncryptUtil.projectIdDesEncrypt(projectId);
            System.err.println(projectId);
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            if (projectIdList == null || projectIdList.isEmpty() || !projectIdList.contains(projectId)) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode());
            }
            if (cloudTalkSDKServerUploadApplePushDTO.getVoip() == null || cloudTalkSDKServerUploadApplePushDTO.getProduction() == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!(cloudTalkSDKServerUploadApplePushDTO.getVoip() == 0 || cloudTalkSDKServerUploadApplePushDTO.getVoip() == 1)
                    || !(cloudTalkSDKServerUploadApplePushDTO.getProduction() == 0 || cloudTalkSDKServerUploadApplePushDTO.getProduction() == 1)
                     || StringUtils.isBlank(cloudTalkSDKServerUploadApplePushDTO.getPassword())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            // 处理业务
            cloudTalkSDKServerUploadApplePushDTO.setProjectId(projectId);
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                //是否是带文件上传的表单
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_UPLOAD_FILE_EMPTY_ERR.getErrorCode());
            }
            MessageVO messageVO = this.uploadApplePushFile(request, cloudTalkSDKServerUploadApplePushDTO);
            if (messageVO != null) {
                return messageVO;
            }
            iCloudTalkSDKServerProjectServiceClient.uploadApplePush(cloudTalkSDKServerUploadApplePushDTO);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "上传苹果推送证书");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK_服务端_项目服务】上传苹果推送证书失败",e);
        }
    }

    /**
     *<desc>
     *      上传苹果推送证书到Http服务器
     *</desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/22
     */
    private MessageVO uploadApplePushFile(HttpServletRequest request,CloudTalkSDKServerUploadApplePushDTO cloudTalkSDKServerUploadApplePushDTO) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String,MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        if (multipartFileMap.isEmpty() || multipartFileMap.size() > 1){
            return new MessageVO(CloudTalkErrorCodeEnum.SERVER_UPLOAD_FILE_EMPTY_ERR.getErrorCode());
        }
        String fileUrl = "";

        String result="";
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = sd.format(new Date());
        String sigParameter = Md5EncryptUtil.md5(String.format("%s%s%s", LYKZ_ACCOUNT_SID, LYKZ_ACCOUNT_TOKEN, nowTime)).toUpperCase();
        String uploadUrl = "http://" + LYKZ_URL + ":" + LYKZ_PORT + "/ucsrtc-rest-api/" + LYKZ_SOFT_VERSION + "/Accounts/" + LYKZ_ACCOUNT_SID + "/uploadCtf";//?sig=" + sigParameter;
        final Base64.Encoder encoder = Base64.getEncoder();
        final String context = String.format("%s%s%s",LYKZ_ACCOUNT_SID,":",nowTime);
        final byte[] textByte = context.getBytes("UTF-8");
        //编码
        final String authorization = encoder.encodeToString(textByte);

        for (String fileKey : multipartFileMap.keySet()) {
            MultipartFile file = multipartRequest.getFile(fileKey);

            // 先上传至第三方服务
            // 服务器的域名
            URL url = new URL(uploadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                // 换行符
                final String newLine = "\r\n";
                final String boundaryPrefix = "--";
                // 定义数据分隔线,这个值是一个随机字符串，不能跟上传的数据一样。
                String BOUNDARY = UUID.randomUUID().toString().replaceAll("-", "");
                // 设置为POST方法
                conn.setRequestMethod("POST");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                // 设置请求头参数
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                OutputStream out = new DataOutputStream(conn.getOutputStream());
                // 拼接数据
                StringBuilder sb = new StringBuilder();
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"authorization\"");
                sb.append(newLine);
                sb.append(newLine);
                sb.append(authorization);
                sb.append(newLine);
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"sig\"");
                sb.append(newLine);
                sb.append(newLine);
                sb.append(sigParameter);
                sb.append(newLine);
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"appId\"");
                sb.append(newLine);
                sb.append(newLine);
                String lykzAppId = iCloudTalkSDKServerProjectServiceClient.getBingLykzAppId(cloudTalkSDKServerUploadApplePushDTO.getProjectId(), PropertyPublicRoleEnum.DEVELOPER.getRoleId(),cloudTalkSDKServerUploadApplePushDTO.getAppId());
                sb.append(lykzAppId);
                sb.append(newLine);
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"voip\"");
                sb.append(newLine);
                sb.append(newLine);
                sb.append(cloudTalkSDKServerUploadApplePushDTO.getVoip());
                sb.append(newLine);
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"production\"");
                sb.append(newLine);
                sb.append(newLine);
                sb.append(cloudTalkSDKServerUploadApplePushDTO.getProduction());
                sb.append(newLine);
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"password\"");
                sb.append(newLine);
                sb.append(newLine);
                sb.append(cloudTalkSDKServerUploadApplePushDTO.getPassword());
                sb.append(newLine);
                sb.append(boundaryPrefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getOriginalFilename() + "\"" + newLine +
                        "Content-Type: application/x-pkcs12");
                sb.append(newLine);
                sb.append(newLine);
                LOG.info(uploadUrl);
                System.err.println(uploadUrl);
                //LOG.info(sb);
                System.err.println(sb);
                // 将参数头的数据写入到输出流中
                out.write(sb.toString().getBytes());
                // 数据输入流,用于读取文件数据
                DataInputStream in = new DataInputStream(file.getInputStream());
                byte[] bufferOut = new byte[1024*8];
                int bytes = 0;
                // 每次读8KB数据,并且将文件数据写入到输出流中
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                // 最后添加换行
                out.write(newLine.getBytes());
                in.close();
                // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
                byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
                // 写上结尾标识
                out.write(end_data);
                out.flush();
                out.close();
                // 定义BufferedReader输入流来读取URL的响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    result += line; // 这里读取的是上边url对应的上传文件接口的返回值，读取出来后，然后接着返回到前端，实现接口中调用接口的方式
                }
                LOG.info(result);
                System.err.println(result);
                if (!result.contains("000000")) {
                    return new MessageVO(CloudTalkErrorCodeEnum.SERVER_UPLOAD_FILE_LONG_DISTANCE_ERR.getErrorCode());
                }

            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            String fileName = file.getOriginalFilename();
            InputStream fileStream = file.getInputStream();
            fileUrl = this.uploadFile(fileStream, fileName);
        }
        cloudTalkSDKServerUploadApplePushDTO.setUrl(fileUrl);
        return null;
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2018/11/22
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.UPLOAD_APPLE_PUSH_CCIE_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

    /**
     * <desc>
     * 上传图片文件
     * <desc/>
     *
     * @param bytes     图片二进制
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-18
     */
    private String uploadImageFile(byte[] bytes, String imageType, FileCatalogEnum fileCatalog) {
        byte[] newbytes = ImgageUtil.stringToImage(bytes, imageType);
        ByteArrayInputStream byteArrayInputStream = null;
        if (newbytes != null) {
            byteArrayInputStream = new ByteArrayInputStream(newbytes);
        } else {
            byteArrayInputStream = new ByteArrayInputStream(bytes);
        }
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );

        try {
            //LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)) {
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            } else {
                LOG.info(String.format("图片上传失败，returnCode: %s", returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }

    /**
     * <desc>
     * 人脸判断
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/11/05
     */
    private SDKMessageVO checkFace(AppCreateBaiduFaceVO appCreateBaiduFaceVO) {
        String checkResult = iIotBaiduFaceServiceClient.faceVerify(appCreateBaiduFaceVO);
        if (checkResult != null && !"".equals(checkResult)) {
            if ("error".equals(checkResult)) {//调用接口异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACEVERFY_ERROR.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("busy".equals(checkResult)) {//调用接口忙
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("others".equals(checkResult)) {//图片不合格,非真人图片
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_PICTURE_ERROR.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("result_num".equals(checkResult)) {//人脸数异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESULTNUM_NOT_1.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("size".equals(checkResult)) {//人脸太小
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_SIZE_TOO_SMALL.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            //2020年8月5号 按照需求说明取消活体检测
           /* if ("faceliveness".equals(checkResult)) {//活体值异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_FACELIVENESS_TOO_LOW.getErrorCode(),appCreateBaiduFaceVO.getRequestId(),appCreateBaiduFaceVO.getResponseTimestamp(),"");
            }*/
            if ("left_eye".equals(checkResult) || "right_eye".equals(checkResult) || "nose".equals(checkResult)
                    || "mouth".equals(checkResult) || "left_cheek".equals(checkResult) || "right_cheek".equals(checkResult)
                    || "chin".equals(checkResult)) {//图片遮挡
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_OCCLUSION.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("blur".equals(checkResult)) {//模糊
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_BLUR_TOO_LOW.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("illumination_min".equals(checkResult)) {//光照过暗
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_LOW.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("illumination_max".equals(checkResult)) {//光照过亮
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_HIGH.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("pitch".equals(checkResult) || "roll".equals(checkResult) || "yaw".equals(checkResult)) {//角度
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ANGLE_NOT_STRAIGHT.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("completeness".equals(checkResult)) {//人脸完整度
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_COMPLETENESS_IMPERFECT.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
        }
        //  2020年8月5号 按照需求说明取消人脸重复比对
      /*  //判断认证图片是否重复
        String repeatResult = iIotBaiduFaceServiceClient.identifyUser(appCreateBaiduFaceVO);
        if (repeatResult != null && !"".equals(repeatResult)) {
            if ("error".equals(repeatResult)) {//调用接口异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_IDENTIFY_ERROR.getErrorCode(),appCreateBaiduFaceVO.getRequestId(),appCreateBaiduFaceVO.getResponseTimestamp(),"");
            }
            if ("busy".equals(repeatResult)) {//调用接口忙
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode(),appCreateBaiduFaceVO.getRequestId(),appCreateBaiduFaceVO.getResponseTimestamp(),"");
            }
            if ("face_repeat".equals(repeatResult)) {//人脸重复注册
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_CREATE_FACE_REPEAT.getErrorCode(),appCreateBaiduFaceVO.getRequestId(),appCreateBaiduFaceVO.getResponseTimestamp(),"");
            }
        }*/
        return null;
    }

    /**
     * <desc>
     * 保存人脸
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/11/05
     */
    private SDKMessageVO saveUserFace(String userId, String uploadFilePath, String requestId,String responseTimestamp,String projectId,String phoneNo,String realName, AppCreateBaiduFaceVO appCreateBaiduFaceVO) throws Exception {
        //保存数据
        AppUserProjectPO appUserProjectPO = new AppUserProjectPO();
        appUserProjectPO.setUserId(userId);
        appUserProjectPO.setProjectId(projectId);
        appUserProjectPO.setFacePicUrl(uploadFilePath);
        appUserProjectPO.setFaceCreateTime(new Date());
        appUserProjectPO.setUpdateTime(new Date());
        appUserProjectPO.setIsFace(2);//认证中
        int updateNumber = iPropertyHouseHoldInfoServiceClient.updatePreUserBaiduFaceInfo(appUserProjectPO);
        if (updateNumber == 0) {
            return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), requestId, responseTimestamp, "");
        }

        //添加人脸注册信息到队列
        appCreateBaiduFaceVO.setProjectId(projectId);
        appCreateBaiduFaceVO.setUserPhone(phoneNo);
        appCreateBaiduFaceVO.setUid(userId);
        appCreateBaiduFaceVO.setUserName(realName);
        appCreateBaiduFaceVO.setUserInfo(realName);//userInfo使用用户名
        appCreateBaiduFaceVO.setUploadFilePath(uploadFilePath);
        boolean resultCreateFace = iIotBaiduFaceServiceClient.createBaiduFace(appCreateBaiduFaceVO);
        if (!resultCreateFace) {
            return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), requestId, responseTimestamp, "");
        }
        return null;
    }

}
